#!/bin/sh
#desc: Opendomo network

IFACE="eth0"
PID_LISTENER="/var/run/oddiscovery-listener.pid"
PID_SENDER="/var/run/oddiscovery-sender.pid"

if test `whoami` != "root"; then
	echo "#ERR This script needs to be executed as root!"
	exit 1
fi

start()
{
	touch $PID_SENDER
   
	if test -z "`cat $PID_LISTENER`" 
	then
		if test -x /usr/bin/oddiscovery-listener
		then
			/usr/bin/oddiscovery-listener $IFACE > /dev/null &
		fi
	else
		echo "Listener is already runnning ..."
	fi

	pidof oddiscovery-listener > $PID_LISTENER


	if test -z "`cat $PID_SENDER`" 
	then
		if test -x /usr/bin/oddiscovery-sender
		then
			/usr/bin/oddiscovery-sender $IFACE > /dev/null &
		fi
	else
		echo "Sender is already runnning ..."
	fi
	
	pidof oddiscovery-sender > $PID_SENDER
	su admin -c /usr/local/opendomo/discovery/processServices.sh >/dev/null
	exit 0
}


stop()
{
	touch $PID_SENDER
	if ! test -z "`cat $PID_SENDER`" 
	then
		kill -9 `cat $PID_SENDER`
		echo "" > $PID_SENDER
	fi

	if ! test -z "`cat $PID_LISTENER`" 
	then
		kill -9 `cat $PID_LISTENER`
		echo "" > $PID_LISTENER
	fi
}


case "$1" in
  start)
	echo -n "Starting OpenDomo Network ..."
	start
   ;;
  stop)
	echo -n "Stopping OpenDomo Network ..."
	stop
   ;;
  status)
   if test -z "`cat $PID_SENDER`" 
	then
		echo "Sender process is not running"
	else
		echo "Sender process is running"
	fi

	if test -z "`cat $PID_LISTENER`"
	then
		echo "Listener process is not running"
	else
		echo "Listener process is running"
	fi
	exit 0
        ;;
  reload|restart)
   stop
   start
   ;;
  *)
   echo $"Usage: $0 {start|stop|restart|reload|status}"
   exit 1
esac



